package com.aube.plugin.gallery;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.aube.plugin.gallery.preview.GalleryPreviewLayout;
import com.aube.plugin.gallery.preview.ImagePreviewActivityHelper;
import com.huyn.baseframework.dynamicload.DLLayout;
import com.huyn.baseframework.dynamicload.DynamicLoaderHelper;
import com.huyn.baseframework.dynamicload.IPositionManager;
import com.huyn.baseframework.model.Category;
import com.huyn.baseframework.model.CategorySimple;
import com.huyn.baseframework.utils.BitmapUtils;
import com.huyn.baseframework.utils.StringUtils;
import com.huyn.baseframework.utils.Utils;
import com.ryg.dynamicload.internal.DLIntent;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by huyaonan on 16/6/17.
 */
public class WidgetGallery extends DLLayout {

    private CategorySimple mCate;
    private GalleryView mGallery;
    private LinearLayout mLayoutGroup;
    private AtomicBoolean mAnimated = new AtomicBoolean(false);
    private View mFlag, mHeadLayout;
    private TextView mMore, mTitle;
    private ImageView mArrow;
    private IPositionManager mManager;

    private GalleryPreviewLayout mGalleryPreviewLayout;

    public WidgetGallery(Context context) {
        this(context, null);
    }

    public WidgetGallery(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public WidgetGallery(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void initViews() {
        inflate(R.layout.widget_gallery, this, true);
        mLayoutGroup = (LinearLayout) findViewById(R.id.gallery_widget_group);

        mFlag = findViewById(R.id.header_flag);
        mTitle = (TextView) findViewById(R.id.header_widget_title);
        mMore = (TextView) findViewById(R.id.header_widget_more);
        mHeadLayout = findViewById(R.id.header_widget_layout);

        mArrow = (ImageView) findViewById(R.id.header_widget_arrow);
        mArrow.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.icon_rightarrow));

        mFlag.setAlpha(0f);
        mTitle.setAlpha(0f);
        mMore.setAlpha(0f);
        mArrow.setAlpha(0f);
    }

    @Override
    public void fillData(Object object) {
        if(object == null || !(object instanceof Category))
            return;
        Category category = (Category) object;
        mCate = category.getSimpleCategory();

        mTitle.setText(category.modelName);

        int count = 0;
        if(category.modelExtra != null) {
            LinkedHashMap<String, Object> modelExtra = (LinkedHashMap<String, Object>) category.modelExtra;

            Object value = modelExtra.get("picCount");
            if(value != null)
                count = (int) ((double) value);
            Object lastIdValue = modelExtra.get("lastid");
            if (lastIdValue != null) {
                try {
                    mLastId = (String) lastIdValue;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        List<PictureImp> pics = PictureImp.parse((List) category.dataDetail);

        if(StringUtils.isNotBlank(category.modelDesc)) {
            mMore.setText(category.modelDesc);
            mHeadLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mBridge != null) {
                        DLIntent intent = new DLIntent("com.aube.plugin.gallery", "com.aube.plugin.gallery.GalleryListActivity");
                        intent.putExtra(GalleryListActivity.GALLERY, mCate);
                        mBridge.openPluginActivity(intent);
                    }
                }
            });
        } else {
            mMore.setVisibility(View.GONE);
            mArrow.setVisibility(View.GONE);
        }

        if(pics != null && pics.size() > 0) {
            mGallery = (GalleryView) DynamicLoaderHelper.loadTargetLayout(context, getDLPluginPackage(), GalleryView.class.getName());
            mLayoutGroup.addView(mGallery, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            mGallery.setDLBridge(mBridge);
            mGallery.setOnGalleryItemClickListener(new OnGalleryItemClickListener() {
                @Override
                public void onClickToList(CategorySimple category) {
                    if (mBridge != null) {
                        DLIntent intent = new DLIntent("com.aube.plugin.gallery", "com.aube.plugin.gallery.GalleryListActivity");
                        intent.putExtra(GalleryListActivity.GALLERY, mCate);
                        mBridge.openPluginActivity(intent);
                    }
                }

                @Override
                public void onClickToPreview(ImageView view, List<PictureImp> pictures, int position) {
                    injectAndOpenGalleryPreview(view, pictures, position);
                }
            });
            mGallery.fillData(mCate, pics, count);

            if(pics.size() >= count)
                mDataLoadFinished = true;
        }
    }

    private void injectAndOpenGalleryPreview(ImageView view, List<PictureImp> pictures, int position) {
        if(mGalleryPreviewLayout == null) {
            mGalleryPreviewLayout = (GalleryPreviewLayout) DynamicLoaderHelper.loadTargetLayout(context, getDLPluginPackage(), GalleryPreviewLayout.class.getName());
            mGalleryPreviewLayout.fillData(mCate.relatedId);

            mGalleryPreviewLayout.setDLBridge(mBridge);

            ((Activity) getContext()).addContentView(mGalleryPreviewLayout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

            if(mBridge != null)
                mBridge.registToReceiveKeyBackGroup(mGalleryPreviewLayout);

            mGalleryPreviewLayout.registLoadListener(new GalleryPreviewLayout.OnLoadMoreListener() {
                @Override
                public void shouldLoadMore() {
                    onLoadMore();
                }
            });
        }

        Bitmap bitmap = BitmapUtils.getBitmapFromDrawable(view);
        ImagePreviewActivityHelper.startPreivew(mGalleryPreviewLayout, view, pictures, bitmap, position, ImagePreviewActivityHelper.LOCATION_TYPE_DEFAULT);
    }

    private boolean mDataLoading = false;
    private boolean mDataLoadFinished = false;
    private String mLastId;
    private void onLoadMore() {
        if(mDataLoading || mDataLoadFinished || StringUtils.isBlank(mLastId))
            return;
        mDataLoading = true;
        getData();
    }

    /**
     * 模块内容接口
     * templateCode(index | actor)
     * ostype(iphone|android)
     * modelCode（template接口中获取）
     * relatedId（有就传，比如嘉宾）
     * lastId（分页用，第一次可不传，当前页最后一个id）
     * maxnum（一页最大条数）
     */
    public void getData() {
        HashMap<String, String> params = new HashMap<>();
        params.put("method", "com.aube.app.model.data");
        params.put("templateCode", mCate.templateType);
        params.put("modelCode", mCate.modelCode);
        params.put("relatedId", mCate.relatedId);
        if(StringUtils.isNotBlank(mLastId))
            params.put("lastId", mLastId);
        params.put("maxnum", "20");
        params.put("subModelCode", mCate.subModelCode);
        if(mBridge != null) {
            mBridge.exeHttpRequest(params, CategoryListModel.class, null, new Response.Listener<CategoryListModel>() {
                @Override
                public void onResponse(CategoryListModel response) {
                    mDataLoading = false;
                    if (response == null || !response.success())
                        return;
                    setupData(response);
                }

                @Override
                public void onErrorResponse(VolleyError error) {
                    mDataLoading = false;
                }

                @Override
                public void onStart() {
                    mDataLoading = true;
                }
            });
        }
    }

    private void setupData(CategoryListModel model) {
        if(model.data == null) {
            return;
        }
        List<Object> contents = null;
        for(CategoryImp category : model.data) {
            if("modelHead".equalsIgnoreCase(category.modelCode)) {
            } else {
                contents = category.dataDetail;
                mLastId = category.lastid;
                if(StringUtils.isBlank(mLastId))
                    mDataLoadFinished = true;
                //sax and setup
                List<PictureImp> mContent = PictureImp.parse(contents);
                if(mGalleryPreviewLayout != null) {
                    mGalleryPreviewLayout.appendData(mContent);
                }
            }
        }
    }

    @Override
    public void notifyAnim(int animDelay) {
        if(mManager == null)
            return;
        if(mAnimated.get())
            return;
        mAnimated.set(true);
        mLayoutGroup.setVisibility(View.VISIBLE);
        showHeader(animDelay);

        if(mGallery != null)
            mGallery.anim(animDelay + 300);
    }

    private void showHeader(int animDelay) {
        ObjectAnimator alphaTitle = ObjectAnimator.ofFloat(mTitle, "alpha", 0, 1);
        alphaTitle.setDuration(300);
        if(animDelay > 0)
            alphaTitle.setStartDelay(animDelay);

        ObjectAnimator alphaDes = ObjectAnimator.ofFloat(mMore, "alpha", 0, 1);
        alphaDes.setDuration(300);
        alphaDes.setStartDelay(200 + animDelay);

        ObjectAnimator alphaArrow = ObjectAnimator.ofFloat(mArrow, "alpha", 0, 1);
        alphaArrow.setDuration(300);
        alphaArrow.setStartDelay(200 + animDelay);

        ObjectAnimator translate = ObjectAnimator.ofFloat(mFlag, "translationY", -mFlag.getHeight(), 0);
        translate.setDuration(300);
        translate.setStartDelay(200 + animDelay);
        translate.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                mFlag.setAlpha(1f);
            }
        });

        AnimatorSet mSet = new AnimatorSet();
        mSet.playTogether(alphaTitle, alphaDes, alphaArrow, translate);
        mSet.start();
    }

    @Override
    public void registToManager(IPositionManager manager) {
        if(mManager != null || manager == null)
            return;
        manager.add(this);
        this.mManager = manager;

        mLayoutGroup.setVisibility(View.INVISIBLE);
    }

    @Override
    public void unreistFromManager(IPositionManager manager) {
        if(mManager == null || manager == null)
            return;
        manager.remove(this);
        this.mManager = null;
    }

    @Override
    public int[] getLocations() {
        int[] locs = new int[2];
        getLocationOnScreen(locs);
        try {
            locs[1] = locs[1] + getHeight() / 2;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return locs;
    }

    @Override
    public void setTheme(int themeColor) {
        mFlag.setBackgroundColor(themeColor);
    }

}
